package modules

import (
	"fmt"
	"log"
	"net/http"
	"net/url"
	"os"
	"path/filepath"
	"strings"
)

// DownloadFile 下载文件
func DownloadFile(w http.ResponseWriter, r *http.Request) {
	PrintRequestInfo(r)
	filename := strings.TrimPrefix(r.URL.Path, "/download/")
	filename, _ = url.QueryUnescape(filename)

	parts := strings.SplitN(filename, "/", 2)
	if len(parts) < 2 {
		log.Printf("指定路径 %s 格式不正确，应为 '根目录名/子路径'", filename)
		EncodeResponse(w, nil, "路径格式错误", http.StatusBadRequest)
		return
	}
	rootName := parts[0]
	subPath := parts[1]
	if _, exists := rootNames[rootName]; !exists {
		log.Printf("指定的根目录名 %s 不存在", rootName)
		EncodeResponse(w, nil, "指定的目录不存在", http.StatusBadRequest)
		return
	}
	targetPath := filepath.Join(rootNames[rootName], subPath)
	info, err := os.Stat(targetPath)
	if err != nil || info.IsDir() {
		log.Printf("指定路径 %s 不存在", targetPath)
		EncodeResponse(w, nil, "指定的文件不存在", http.StatusBadRequest)
		return
	}
	if IsPathOutOfScope(targetPath, rootName, w) {
		return
	}
	// 判定是否为预览请求
	isPreview := r.URL.Query().Get("preview") == "true"
	if !isPreview {
		// 仅在下载请求时设置 Content-Disposition
		w.Header().Set("Content-Disposition", fmt.Sprintf("attachment; filename=%s", filepath.Base(targetPath)))
	}
	http.ServeFile(w, r, targetPath)
}
